package com.bbcare.treat.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.store.ibatis.IPatientOperationRecordDAO;
import com.bbcare.treat.plat.entity.BsContentConfig;
import com.bbcare.treat.plat.service.IPublicConfigService;
import com.bbcare.treat.plat.store.ibatis.IBsContentConfigDAO;

/**
 * @name: 随访诊疗系统（基因等）项目管理相关接口实现
 * @author: DemonLee
 * @createTime: 2017.11.29
 * @description:
 * @modify:
 *
 */
@Service
public class PublicConfigService implements IPublicConfigService {
    private final Log logger = LogFactory.getLog(PublicConfigService.class);

    @Autowired
    public IBsContentConfigDAO bsContentConfigDao;

    @Autowired
    private IPatientInfoHisService patientInfoHisService;

    @Autowired
    private IPatientOperationRecordDAO patientOperationRecordDao;

    // 查询项目
    @Override
    public Map<String, Object> listProjectItem(Map<String, Object> mapIn) throws Exception {
        Map<String, Object> mapOut = new HashMap<String, Object>();
        List<BsContentConfig> outList = new ArrayList<BsContentConfig>();

        mapIn.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        outList = bsContentConfigDao.listBsContentConfig(mapIn);
        int total = 0;
        if (CollectionUtils.isNotEmpty(outList)) {
            total = outList.size();
        }
        mapOut.put("rows", outList);
        mapOut.put("total", total);

        return mapOut;
    }

    // 添加项目
    @Override
    @Transactional
    public Map<String, Object> saveNewProjectItem(Map<String, Object> argMap) throws Exception {
        Map<String, Object> mapOut = new HashMap<String, Object>();
        Map<String, Object> mapIn = new HashMap<String, Object>(argMap);
        Map<String, Object> oprInfo = ToolUtils.typeCast(mapIn.get("oprInfo"));
        Map<String, Object> projectInfo = ToolUtils.typeCast(mapIn.get("projectInfo"));
        Map<String, Object> sessionInfo = ToolUtils.typeCast(mapIn.get("sessionInfo"));
        String tenantId = (String) sessionInfo.get("tenantId");
        String authorId = (String) sessionInfo.get("authorId");
        String updateTime = (String) oprInfo.get("updateTime");
        String updateAccept = (String) oprInfo.get("updateAccept");
        String configName = (String) projectInfo.get("configName");
        String configCode = (String) projectInfo.get("configCode");
        String configType = (String) projectInfo.get("configType");
        String queueId = (String) projectInfo.get("queueId");

        // 查询当前租户该题型下是否已经有了该项目
        BsContentConfig bccVo = null;
        String bccId = null;
        Map<String, Object> qryMapIn = new HashMap<String, Object>();
        qryMapIn.put("configType", configType);
        qryMapIn.put("configName", configName);
        qryMapIn.put("configCode", configCode);
        qryMapIn.put("tenantId", tenantId);
        List<BsContentConfig> bccList = bsContentConfigDao.listBsContentConfig(qryMapIn);
        if (CollectionUtils.isNotEmpty(bccList)) {
            // 已存在，则判断状态
            bccVo = bccList.get(0);
            String status = bccVo.getStatus();
            if (Constants.TABLE_RECORD_STATUS_NOMAL.equals(status)) {
                // 正常状态，报错返回
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_CONTENTCONFIG_ALREADY_EXIST,
                        "该项目【" + configName + "】已存在，请勿重复添加！"));
            } else {
                // 更新为正常状态（重复使用原有数据）
                bccId = bccVo.getId();
                logger.info("---exist bccVo.(id,status)==(" + bccId + "," + status + ")");

                qryMapIn.clear();
                qryMapIn.put("id", bccId);
                qryMapIn.put("tenantId", tenantId);
                qryMapIn.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
                qryMapIn.put("updateAccept", updateAccept);
                qryMapIn.put("updateTime", updateTime);
                qryMapIn.put("updateAuthor", authorId);
                bsContentConfigDao.updateBsContentConfig(qryMapIn);
                // 入历史
                qryMapIn.remove("status");
                qryMapIn.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
                bsContentConfigDao.saveBsContentConfigHis(qryMapIn);
            }
        } else {
            qryMapIn.remove("configName");
            int seqNo = bsContentConfigDao.countBsContentConfig(qryMapIn);
            // 新增
            bccId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_CONTENT_CONFIG_PROJECT_ID);
            bccVo = new BsContentConfig();
            bccVo.setConfigCode(configCode);
            bccVo.setConfigName(configName);
            bccVo.setConfigType(configType);
            bccVo.setConfigValue((String) projectInfo.get("configValue"));
            bccVo.setCreateAuthor(authorId);
            bccVo.setCreateTime(updateTime);
            bccVo.setHisCode((String) projectInfo.get("hisCode"));
            bccVo.setId(bccId);
            bccVo.setQueueId(queueId);
            bccVo.setSeqNo(seqNo + 1);
            bccVo.setShowFlag(Constants.CONTENT_CONFIG_SHOW_FLAG_01);
            bccVo.setStatus(Constants.TABLE_RECORD_STATUS_NOMAL);
            bccVo.setTenantId(tenantId);
            bccVo.setUpdateAccept(updateAccept);
            bccVo.setUpdateAuthor(authorId);
            bccVo.setUpdateTime(updateTime);
            bsContentConfigDao.saveBsContentConfig(bccVo);
            // 入历史
            qryMapIn.clear();
            qryMapIn.put("id", bccId);
            qryMapIn.put("tenantId", tenantId);
            qryMapIn.put("updateType", Constants.UPDATE_TYPE_INSERT);
            qryMapIn.put("updateAccept", updateAccept);
            qryMapIn.put("updateTime", updateTime);
            qryMapIn.put("updateAuthor", authorId);
            bsContentConfigDao.saveBsContentConfigHis(qryMapIn);
        }

        // 操作记录
        Map<String, Object> paramRecord = new HashMap<String, Object>();
        paramRecord.put("userName", "");
        paramRecord.put("userId", "");
        paramRecord.put("queueId", queueId);
        paramRecord.put("authorId", authorId);
        paramRecord.put("opTime", updateTime);
        paramRecord.put("type", Constants.DOCTOR_ACTIVE_BUSI_TYPE_10);
        paramRecord.put("opUsertype", Constants.OPCODE_TYPE_DOCTOR);
        paramRecord.put("authorName", (String) sessionInfo.get("authorName"));
        paramRecord.put("opCode", (String) oprInfo.get("opCode"));
        paramRecord.put("updateAccept", updateAccept);
        paramRecord.put("tenantId", tenantId);
        paramRecord.put("remark", (String) oprInfo.get("opNote"));
        paramRecord.put("opType", (String) oprInfo.get("opType"));
        paramRecord.put("taskId", "");
        paramRecord.put("busiId", bccId);
        Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
        patientOperationRecordDao.saveOperationRecord(outRecord);

        mapOut.put("id", bccId);
        return mapOut;
    }

    // 修改项目
    @Override
    @Transactional
    public Map<String, Object> modifyProjectItem(Map<String, Object> argMap) throws Exception {
        Map<String, Object> mapOut = new HashMap<String, Object>();
        Map<String, Object> mapIn = new HashMap<String, Object>(argMap);
        Map<String, Object> oprInfo = ToolUtils.typeCast(mapIn.get("oprInfo"));
        Map<String, Object> projectInfo = ToolUtils.typeCast(mapIn.get("projectInfo"));
        Map<String, Object> sessionInfo = ToolUtils.typeCast(mapIn.get("sessionInfo"));
        String tenantId = (String) sessionInfo.get("tenantId");
        String authorId = (String) sessionInfo.get("authorId");
        String updateTime = (String) oprInfo.get("updateTime");
        String updateAccept = (String) oprInfo.get("updateAccept");
        String id = (String) projectInfo.get("id");
        String configCode = (String) projectInfo.get("configCode");
        String configType = (String) projectInfo.get("configType");
        String queueId = "";

        // 查询当前租户该题型下是否已经有了该项目
        Map<String, Object> qryMapIn = new HashMap<String, Object>();
        qryMapIn.put("configType", configType);
        qryMapIn.put("id", id);
        qryMapIn.put("configCode", configCode);
        qryMapIn.put("tenantId", tenantId);
        List<BsContentConfig> bccList = bsContentConfigDao.listBsContentConfig(qryMapIn);
        if (CollectionUtils.isNotEmpty(bccList)) {
            queueId = bccList.get(0).getQueueId();
            String status = bccList.get(0).getStatus();
            if (Constants.TABLE_RECORD_STATUS_INVALID.equals(status)) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_CONTENTCONFIG_WAS_REMOVED, "该项目已删除，处理失败！"));
            }
            // 更新
            projectInfo.put("tenantId", tenantId);
            projectInfo.put("updateAccept", updateAccept);
            projectInfo.put("updateTime", updateTime);
            projectInfo.put("updateAuthor", authorId);
            bsContentConfigDao.updateBsContentConfig(projectInfo);
            // 入历史
            projectInfo.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
            bsContentConfigDao.saveBsContentConfigHis(projectInfo);
        } else {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_CONTENTCONFIG_NOT_EXIST, "未查询到该项目，处理失败！"));
        }

        // 操作记录
        Map<String, Object> paramRecord = new HashMap<String, Object>();
        paramRecord.put("userName", "");
        paramRecord.put("userId", "");
        paramRecord.put("queueId", queueId);
        paramRecord.put("authorId", authorId);
        paramRecord.put("opTime", updateTime);
        paramRecord.put("type", Constants.DOCTOR_ACTIVE_BUSI_TYPE_10);
        paramRecord.put("opUsertype", Constants.OPCODE_TYPE_DOCTOR);
        paramRecord.put("authorName", (String) sessionInfo.get("authorName"));
        paramRecord.put("opCode", (String) oprInfo.get("opCode"));
        paramRecord.put("updateAccept", updateAccept);
        paramRecord.put("tenantId", tenantId);
        paramRecord.put("remark", (String) oprInfo.get("opNote"));
        paramRecord.put("opType", (String) oprInfo.get("opType"));
        paramRecord.put("taskId", "");
        paramRecord.put("busiId", id);
        Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
        patientOperationRecordDao.saveOperationRecord(outRecord);

        return mapOut;
    }
}
